try:
  import usocket as socket
except:
  import socket
from machine import Pin,PWM

#定义对象 红/绿/蓝LED控制的PWM 输出
rgbR = PWM(Pin(18), freq=1000,duty=0)
rgbG = PWM(Pin(5), freq=1000,duty=0)
rgbB = PWM(Pin(19), freq=1000,duty=0)

# 设置颜色函数
def set_color(red, green, blue):
    rgbR.duty(int(red * 1023 / 255))
    rgbG.duty(int(green * 1023 / 255))
    rgbB.duty(int(blue * 1023 / 255))
    print('set ',red,green,blue,'success')

#将16进制颜色码转为RGB值
def coler_HexDec(hex_color):
    try:
        r = int(hex_color[0:2], 16)
        g = int(hex_color[2:4], 16)
        b = int(hex_color[4:6], 16)
        set_color(r,g,b)
    except Exception as e:
        print(e)
        
# html code
def web_page():  

    html ='''
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>ESP32</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 20px;
        }
        .color-display {
            width: 100px;
            height: 100px;
            border: 1px solid #000;
            margin-top: 10px;
        }
    </style>
</head>
<body>
<h1>选择颜色</h1>
<form id="colorForm" action="/setColor" method="GET">
    <label for="colorPicker">选择颜色: </label>
    <input type="color" id="colorPicker" name="color" value="#ff0000">
    <button type="submit">提交</button>
</form>
<div class="color-display" id="colorDisplay"></div>

<script>
    // Getting references to the DOM elements
    const colorPicker = document.getElementById('colorPicker');
    const colorDisplay = document.getElementById('colorDisplay');
    const colorForm = document.getElementById('colorForm');

    // Function to convert hex color code to RGB
    function hexToRgb(hex) {
        let bigint = parseInt(hex.slice(1), 16); // Convert hex to integer
        let r = (bigint >> 16) & 255; // Extract red component
        let g = (bigint >> 8) & 255;  // Extract green component
        let b = bigint & 255;         // Extract blue component
        return {r, g, b};             // Return RGB as an object
    }

    // Event listener to update the color display background
    colorPicker.addEventListener('input', function () {
        colorDisplay.style.backgroundColor = colorPicker.value;
    });

    // Event listener to set the form action URL with RGB values on submit
    colorForm.addEventListener('submit', function (event) {
        event.preventDefault(); // Prevent default form submission
        const color = colorPicker.value;
        const rgb = hexToRgb(color);
        colorForm.action = `/setColor?r=${rgb.r}&g=${rgb.g}&b=${rgb.b}`;
        colorForm.submit(); // Programmatically submit the form after setting the action
    });
</script>
</body>
</html>
'''
    return html

#建立socket套字
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(('', 80))
s.listen(5)

while True:
    conn, addr = s.accept()
    print('Got a connection from %s' % str(addr))
    request = conn.recv(1024)
    print('decoding...')
    request = request.decode()
    request = str(request)
    #查找url中的颜色值
    ns_index = request.find('%23')
    ns_index = ns_index + 2
    color_index = ns_index + 6
    color = request[ns_index+1:color_index+1]
    coler_HexDec(color)
    response = web_page()
    conn.sendall(response)
    conn.close()
